package com.lyb.service;

import com.spring.BeanPostProcessor;
import com.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Sobremesa
 * @version 1.0.0
 * @ClassName LybBeanPostProcessor.java
 * @Description TODO
 * @createTime 2021年08月16日 15:44:00
 */
@Component
public class LybBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessorBeforeInitialization(Object bean, String beanName) {

        System.out.println("初始化前");
        if ("userService".equals(beanName)){
            ((UserServiceImpl)bean).setName("liyunbo");
        }

        return bean;
    }

    /**
     *AOP的最简单实现，基于postProcessorAfterInitialization(beanpostProcessor的子类)方法，基于动态代理
     */
    @Override
    public Object postProcessorAfterInitialization(Object bean, String beanName) {
        System.out.println("初始化后");

        if ("userService".equals(beanName)) {

            //JDK的动态代理
            Object proxyInstance = Proxy.newProxyInstance(LybBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    //先执行代理逻辑
                    System.out.println("代理逻辑");     //找对应的切点
                    //再去执行真正方法
                    return method.invoke(bean,args);
                }
            });
            //直接返回生成的代理对象
            return proxyInstance;

        }

        return bean;
    }
}
